package dhee.wtqshopproject.utils;

import dhee.wtqshopproject.dao.CartMapper;
import dhee.wtqshopproject.entity.Cart;
import dhee.wtqshopproject.entity.User;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
public class CartUtils {

    private static CartUtils cartUtils;  // 静态实例

    @Resource
    private CartMapper cartMapper;

    // 初始化静态实例和Mapper
    @PostConstruct
    public void init() {
        cartUtils = this;
        cartUtils.cartMapper = this.cartMapper;
    }

    // 通用用户登录校验方法
    private static void checkUserLogin() {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("请先登录");
        }
    }

    // 1. 添加商品到购物车
    public static void addToCart(Cart cart) {
        checkUserLogin();
        // 设置用户ID为当前登录用户
        cart.setUserId(UserContext.getCurrentUser().getUserId());
        cartUtils.cartMapper.insertCart(cart);
    }

    // 2. 查询当前用户的购物车全部商品
    public static List<Cart> getCartItems() {
        checkUserLogin();
        Integer userId = UserContext.getCurrentUser().getUserId();
        return cartUtils.cartMapper.selectCartByUserId(userId);
    }

    // 3.1 删除单个购物车项
    public static void removeCartItem(Integer cartId) {
        checkUserLogin();
        Integer userId = UserContext.getCurrentUser().getUserId();
        Cart cart1 = cartUtils.cartMapper.selectCartById(cartId);
        // 验证该cartId是否属于当前用户
      if (cart1.getUserId().equals(userId)) {
        cartUtils.cartMapper.deleteCartItem(cartId);}
      else {
          System.out.println("不是你的购物车，无法删除");
      }
    }

    // 3.2 清空当前用户的购物车
    public static void clearCart() {
        checkUserLogin();
        Integer userId = UserContext.getCurrentUser().getUserId();
        cartUtils.cartMapper.clearCart(userId);
    }

    // 4. 修改购物车商品数量
    public static void updateCartItemQuantity(Integer productId, Integer quantity) {
        checkUserLogin();
        Integer userId = UserContext.getCurrentUser().getUserId();
        System.out.println("userId = " + userId);

        // 验证用户是否有该商品的购物车记录
        List<Cart> userCarts = cartUtils.cartMapper.selectCartByUserId(userId);
        System.out.println("userCarts = " + userCarts);
        boolean hasProduct = userCarts.stream()
                .anyMatch(c -> c.getProductId().equals(productId));
        if (!hasProduct) {
            throw new RuntimeException("购物车中无此商品");
        }

        cartUtils.cartMapper.updateQuantity(userId, productId, quantity);
    }

    // 辅助方法：根据cartId查询购物车项
    private static List<Cart> selectCartById(Integer cartId) {
        return cartUtils.cartMapper.selectCartByUserId(cartId);
    }
}